/**
 * @Author: jipeng.Li
 * @Date:  2021-04-19 08:22:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-04-20 11:54:21
 * @Description: 维修卡
 */
import React, { Component } from 'react';
import {
  Linking, Modal,
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from 'react-native';
import {
  fontColorBlack,
  fontColorCoffee,
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp,
  screenHeight
} from '@/styles';
import { msg, Loading } from '@/common';
import QRCode from 'react-native-qrcode-svg';
import user from '@/api/user';
import wlRepair from '@/api/repair';
import RepairCard from './components/repair-card';

export default class CardDetails extends Component {
  constructor(props) {
    super(props);
    this.state = {
      customerPhone: [], // 客服电话
      qrCodeCountDown: 59,
      qrCode: '', // 二维码字符串
      userType: null, // 用户类型 1 车主 2 司机,
      cardData: {}, // 维修卡数据,
      isWriteOff: false,
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { cardData } = params;
    this.setState({ cardData }, () => {
      this.getAuthById();
    });
    msg.on('setUpWlRepairQrCodeInterval', () => {
      this.setState({ qrCodeCountDown: 59 }, () => this.setUpQrCodeInterval(true));
    });
    this.getConfigValue();
  }

  componentWillUnmount() {
    this.setUpQrCodeInterval(false);
  }

  oilCardBtn = {
    1: [
      { id: 0, text: '交易记录', routerName: 'WlRepairTradeRecord' },
      { id: 1, text: '共享维修卡', routerName: 'WlRepairShareRecord' },
    ],
    2: [
      { id: 0, text: '交易记录', routerName: 'WlRepairTradeRecord' },
    ],
  }

  render() {
    const { customerPhone, qrCode, userType, cardData, isWriteOff } = this.state;
    const { enterpriseStatus, status } = cardData;
    return (
      <SafeAreaView style={styles.container}>
        {
          userType && (
            <>
              <View style={styles.detailsContainer}>
                <View style={styles.oilCardContainer}>
                  <RepairCard
                    companyType={cardData.caronwerCustName}
                    companyName={cardData.carOwnerMobile}
                    balance={cardData.nowAmount || cardData.total}
                    renderBottomContent={this.getOilCarTabData()}
                    bottomContentClick={tab => this.routerJump(tab.routerName)}
                  />
                </View>
                {
                  (enterpriseStatus === 'N' || status === 'N') || (
                    <>
                      <View style={styles.detailsDataContainer}>
                        {this.verificationTypeTitle()}
                        <View style={{ alignItems: 'center', marginVertical: px2dp(20) }}>
                          {
                            (qrCode !== '') && (
                              <QRCode
                                value={qrCode}
                                logoBorderRadius={1}
                                color='#191919'
                                backgroundColor='#ffffff'
                                logoSize={30}
                                size={screenHeight / 5}
                              />
                            )
                          }
                          {this.verificationState()}
                        </View>
                      </View>
                      {
                        userType === 2 && (
                          <View style={styles.detailsTipsContainer}>
                            <Text style={styles.detailsTipsText}>
                              {cardData.empowerNum ? `剩余${cardData.empowerNum}次可用` : null}
                            </Text>
                            <Text
                              style={[styles.detailsTipsText, { borderLeftWidth: px2dp(2), borderLeftColor: '#F5F5F5' }]}
                            >
                              {`${cardData.empowerEndTime}到期`}
                            </Text>
                          </View>
                        )
                      }
                    </>
                  )
                }
              </View>
              <TouchableOpacity
                onPress={this.callServicePhone}
                style={{ alignItems: 'center', marginBottom: px2dp(20) }}
              >
                <Text>
                  客服电话：
                  {customerPhone.length > 0 ? customerPhone[0].keys : ''}
                </Text>
              </TouchableOpacity>
            </>
          )
        }
      </SafeAreaView>
    );
  }

  verificationTypeTitle = () => {
    const { userType, cardData } = this.state;
    const { driverName, driverMobile } = cardData;
    if (userType && userType === 1) {
      return <Text style={{ color: fontColorBlack }}>车主修理卡二维码</Text>;
    }

    return (
      <Text style={{ fontSize: px2dp(28) }}>
        <Text style={{ color: '#999793' }}>授权司机：</Text>
        <Text style={{ color: fontColorBlack }}>
          {`${driverName} ${driverMobile}`}
        </Text>
      </Text>
    );
  }

  verificationState = () => {
    const { qrCodeCountDown, isWriteOff } = this.state;
    return (
      <Text style={{ fontSize: px2dp(28), marginTop: px2dp(20) }}>
        {isWriteOff ? (
          <Text style={{ color: '#999793' }}>正在核销中...  </Text>
        ) : (
          <>
            <Text style={{ color: '#999793' }}>剩余刷新时间 </Text>
            <Text style={{ color: fontColorCoffee }}>{` ${qrCodeCountDown}s`}</Text>
          </>
        )}
      </Text>
    );
  }

  // 获取油卡tab数据
  getOilCarTabData = () => {
    const { userType, cardData } = this.state;
    const { enterpriseStatus, status } = cardData;
    if (userType === 1 && (enterpriseStatus === 'N' || status === 'N')) {
      return [this.oilCardBtn[userType][0]];
    }
    return this.oilCardBtn[userType];
  }

  // 刷新二维码
  refreshQrCode = () => {
    this.qrCodeCount && clearInterval(this.qrCodeCount);
    this.qrCodeCount = setInterval(() => {
      const { qrCodeCountDown } = this.state;
      let time = qrCodeCountDown;
      if (!time) {
        this.setState({ qrCodeCountDown: 59, qrCode: '' }, () => {
          this.getQrCode();
        });
        return;
      }
      this.setState({ qrCodeCountDown: --time });
    }, 1000);
  }

  // 油卡tab点击
  routerJump = (routeName) => {
    this.setUpQrCodeInterval(false);
    const { cardData } = this.state;
    if (cardData.accountCarownerId && this.timer) {
      this.timer = null;
      msg.emit('router: goToNext', {
        routeName,
        cardData
      });
    }
  }

  // 拨打电话
  callServicePhone = () => {
    const { customerPhone } = this.state;
    if (customerPhone.length <= 0) return;
    const url = `tel:${customerPhone[0].keys}`;
    Linking.canOpenURL(url)
      .then(supported => {
        if (!supported) {
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '提示',
            text: '您的设备不支持该功能，请手动拨打${phone}',
            okText: '确定',
            isClickBg: false,
          });
          return;
        }
        return Linking.openURL(url);
      }).catch((err) => {
        msg.emit('app:tip', { text: err });
      });
  };

  // 开启或关闭二维码请求刷新和核销结果轮询 true 开启 | false 关闭
  setUpQrCodeInterval = (flag) => {
    if (flag) {
      this.getAuthById();
    } else {
      clearInterval(this.qrCodeCount);
      clearTimeout(this.timer);
    }
  }

  /**
   * 接口
   */
  // 请求核销卡数据
  getAuthById = () => {
    const { cardData } = this.state;
    wlRepair.repairGetAuthById({ id: cardData.id }).then(res => {
      if (res.success) {
        this.setState({ cardData: res.data, userType: res.data.type }, () => {
          this.getQrCode();
        });
      } else {
        msg.emit('app:tip', { text: res.msg || '连接错误' });
        msg.emit('router: back');
      }
    });
  }

  // 获取二维码
  getQrCode = () => {
    const { cardData } = this.state;
    if (cardData.id) {
      wlRepair.maincode({ id: cardData.id }).then(res => {
        if (res.success) {
          this.setState({
            qrCode: res.data,
            pumpOilNo: res.data.match(/:(\S*):/)[1],
          }, () => {
            this.refreshQrCode();
            this.verificationSuccess();
          });
        }
      });
    }
  }

  // 是否核销成功
  // 接口返回： 0未核销 | 1 已核销 | 2 已退款 | 3已失败 | 4核销中
  verificationSuccess = () => {
    const { pumpOilNo } = this.state;
    this.timer && clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      wlRepair.verificationSuccess({ maintenancelNo: pumpOilNo }).then(res => {
        if (res.success) {
          const { writeOffStatus, reason, writeOffAmount } = res.data;
          switch (writeOffStatus) {
          case 0: // 0未核销
            this.verificationSuccess();
            break;
          case 1: // 1 已核销
            this.setUpQrCodeInterval(false);
            this.setState({ isWriteOff: false });
            msg.emit('app:messageBox', {
              isVisible: true,
              title: '提 示',
              text: `核销金额：${writeOffAmount}元`,
              okText: '确定',
              isClickBg: false,
              okFn: () => {
                msg.emit('router: refreshRoute', {
                  routeName: 'WlRepair',
                });
                msg.emit('router: back');
              },
            });
            break;
          case 3: // 3 已失败
            this.setUpQrCodeInterval(false);
            this.setState({ isWriteOff: false });
            msg.emit('app:messageBox', {
              isVisible: true,
              title: '提 示',
              text: res.msg || '核销失败',
              okText: '重试',
              isClickBg: false,
              okFn: () => {
                this.setState({ qrCodeCountDown: 59 }, () => {
                  this.setUpQrCodeInterval(true);
                });
              },
            });
            break;
          case 4: // 4 核销中
            clearInterval(this.qrCodeCount);
            this.setState({ isWriteOff: true });
            this.verificationSuccess();
            break;
          }
        } else {
          this.setState({ isWriteOff: false });
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '未知错误',
            text: res.msg,
            okText: '确定',
            isClickBg: false,
            okFn: () => {
              this.setUpQrCodeInterval(false);
              msg.emit('router: back');
            },
          });
        }
      });
    }, 2000);
  }

  // 获取客服电话
  getConfigValue = () => {
    user.getConfigValue({
      codes: ['kjgskfdh']
    }).then(res => {
      if (res.success) {
        this.setState({
          customerPhone: res.data
        });
      } else {
        this.setState({
          customerPhone: []
        });
      }
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    paddingHorizontal: px2dp(20),
    justifyContent: 'space-between'
  },
  detailsContainer: {
    flex: 1,
    position: 'relative',
    backgroundColor: mainBgColorWhite,
    borderRadius: px2dp(24),
    marginTop: '25%',
    marginBottom: '40%',
  },
  oilCardContainer: {
    position: 'absolute',
    top: px2dp(-155),
    width: '100%',
    alignItems: 'center',
  },
  detailsDataContainer: {
    flex: 1,
    marginTop: px2dp(155),
    alignItems: 'center',
    paddingVertical: '13%',
    borderBottomRightRadius: px2dp(24),
    borderBottomLeftRadius: px2dp(24),
    justifyContent: 'space-between',
  },
  detailsTipsContainer: {
    position: 'absolute',
    bottom: px2dp(-75),
    height: px2dp(96),
    width: '100%',
    backgroundColor: '#FAFAF9',
    borderBottomRightRadius: px2dp(24),
    borderBottomLeftRadius: px2dp(24),
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center'
  },
  detailsTipsText: {
    flex: 1,
    fontSize: px2dp(28),
    color: '#999793',
    textAlign: 'center'
  },
});
